package kr.ac.jbnu.appcenter.android.ball_game;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public class BallGameActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		MyView mv = new MyView(this);
		setContentView(mv);
	}

	class MyView extends View {

		Handler handler = new Handler() {
		    public void handleMessage(Message msg) {
		    	r -= 3;
		    	if (r < 0) {
		    		Toast.makeText(getBaseContext(), "You lose:[" + count + "]", Toast.LENGTH_SHORT).show();
		    		return;
		    	}
		    	
		    	handler.sendEmptyMessageDelayed(0, speed);
				invalidate();
		    }
		};
		
		float x, y, r;
		RectF rectF;
		
		int displayWidth;
		int displayHeight;
		
		static final int radius = 70;
		
		Random rand = new Random();
		Paint paint = new Paint();
		
		int count = 0;
		int speed = 50;
		
		Toast toast;
		
		public MyView(Context context) {
			super(context);
			
			WindowManager winMgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
			displayWidth = winMgr.getDefaultDisplay().getWidth();
			displayHeight = winMgr.getDefaultDisplay().getHeight();
			
			makeCircle();
			
			handler.sendEmptyMessage(0);
		}
		
		
		public void onDraw(Canvas canvas) {
			canvas.drawColor(Color.LTGRAY);			
			
			canvas.drawCircle(x, y, r, paint);
		}
		
		public void makeCircle() {
			paint.setColor(Color.rgb(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
			
			x = rand.nextInt(displayWidth-(2*radius)) + radius;
			y = rand.nextInt(displayHeight-(2*radius)) + radius;
			r = radius;
			
			rectF = new RectF(x - r, y - r, x + r, y + r);
			
			if (speed > 25)
				speed--;
			
			if (toast == null) 
				toast = Toast.makeText(getBaseContext(), "w: " + displayWidth + " h: " + displayHeight + " x: " + x + " y: " + y, Toast.LENGTH_SHORT); 
			else 
				toast.setText("speed: " + speed + "w: " + displayWidth + " h: " + displayHeight + " x: " + x + " y: " + y);
			toast.show();
		}

		public boolean onTouchEvent(MotionEvent event) {			
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if ( rectF.contains(event.getX(), event.getY()) ) {
					count ++;
					makeCircle();
					
					invalidate();					
				}
				
				return true;
			}
			return false;			
		}

	}
}